package com.md.config.database.slave.balancer;

import com.md.config.database.slave.DataSourceProperty;
import com.md.util.ObjectUtil;

import java.util.List;

public class RotationSlaveSourceLoadBalancer extends ISlaveSourceLoadBalancer {
  private Integer currentIndex;

  public RotationSlaveSourceLoadBalancer() {
    currentIndex = 0;
  }

  public static RotationSlaveSourceLoadBalancer of() {
    return new RotationSlaveSourceLoadBalancer();
  }

  @Override
  public String load(final List<DataSourceProperty> dataSourceConfigs) {
    if (ObjectUtil.isEmpty(dataSourceConfigs)) {
      return null;
    }
    String unique = dataSourceConfigs.get(currentIndex).getUnique();
    // 轮询选择下一个从库
    currentIndex = (currentIndex + 1) % dataSourceConfigs.size();
    return unique;
  }
}
